'use strict';
const db = uniCloud.database()
const ordersCollection = db.collection('orders')
const $ = db.command.aggregate

exports.main = async (event, context) => {
	const { orderId } = event
	
	try {
		if (!orderId) {
			return {
				code: -1,
				msg: '订单ID不能为空'
			}
		}
		
		// 聚合查询订单信息和关联的课程信息
		const orderDetail = await ordersCollection
			.aggregate()
			.match({
				_id: orderId
			})
			.lookup({
				from: 'courses',
				localField: 'courseId',
				foreignField: '_id',
				as: 'courseInfo'
			})
			.project({
				_id: 1,
				courseId: 1,
				status: 1,
				createTime: 1,
				price: 1,
				paymentMethod: 1,
				courseInfo: $.arrayElemAt(['$courseInfo', 0])
			})
			.end()
		
		if (!orderDetail.data || orderDetail.data.length === 0) {
			return {
				code: -1,
				msg: '订单不存在'
			}
		}
		
		return {
			code: 0,
			msg: '获取成功',
			data: orderDetail.data[0]
		}
	} catch (e) {
		return {
			code: -1,
			msg: '获取失败',
			error: e
		}
	}
}; 